<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<style>
  .box {
      width: 100px;
      height: 100px;
      background: red;
  }
</style>
<body>
<!--
调用下面的 downloadImg 模拟并发下载
要求:一共有 12 个图片，同一时间的并发数不超过4个，每下载完一张图片休息 100ms

function downloadImg() {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = function () {
      console.log('loaded')
      resolve()
    }
    img.onerror = reject
    img.src = null
  })
}
-->
<div class="box"></div>
</body>
<script>
  function downPng() {
    html2canvas(document.querySelector("#preview-content")).then(canvas => {
      console.log(canvas.toDataURL('image/jpeg'))
    });
  }
  downPng()

  async function downloadImgs() {
    const urls = [
      'img1.jpg',
      'img2.jpg',
      'img3.jpg',
      'img4.jpg',
      'img5.jpg',
      'img6.jpg',
      'img7.jpg',
      'img8.jpg',
      'img9.jpg',
      'img10.jpg',
      'img11.jpg',
      'img12.jpg'
    ];

    const maxConcurrentDownloads = 4;
    let currentlyDownloading = 0;

    while (urls.length > 0) {
      const batchCount = Math.min(urls.length, maxConcurrentDownloads - currentlyDownloading);
      const batchUrls = urls.splice(0, batchCount);

      const batchPromises = batchUrls.map(url => {
        return new Promise((resolve, reject) => {
          const img = new Image();
          img.onload = function() {
            console.log('loaded ' + url);
            resolve();
          };
          img.onerror = reject;
          img.src = url;
        });
      });

      const resolvedPromises = await Promise.all(batchPromises);
      currentlyDownloading -= resolvedPromises.length;

      // 等待100ms
      await new Promise(resolve => setTimeout(resolve, 100));
    }
  }

  downloadImgs();
</script>
</html>
